package com.heer.gymnasium.module.coach.views;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.bigkoo.svprogresshud.SVProgressHUD;
import com.heer.amap.utils.ToastUtil;
import com.heer.gymnasium.R;
import com.heer.gymnasium.api.ResponseData.ApiResponse;
import com.heer.gymnasium.api.callback.BaseCallback;
import com.heer.gymnasium.base.BaseActivity;
import com.heer.gymnasium.util.Base64Util;
import com.heer.gymnasium.util.SDCardUtils;
import com.zhihuiyun.library.utils.BitmapUtils;
import com.zhihuiyun.library.view.TouchImageView;

import java.io.File;

import butterknife.BindView;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Response;

/**
 * Created by yan on 2018/1/18.
 * 私教核销界面
 */

public class CoachVerificationActivity extends BaseActivity {
    private static final int RES_ID_LAYOUT = R.layout.layout_coach_auth;
    private static final int RES_ID_HEAD = R.id.layout_coach_auth_head_iv;
    private static final int RES_ID_RESET = R.id.layout_coach_auth_reset_tv;
    private static final int RES_ID_AUTH = R.id.layout_coach_auth_tv;

    private static final int PHOTO_GRAPH = 0xF;
    private static final int REQUEST_CODE_CONTACT = 1;

    @BindView(RES_ID_AUTH)
    TextView tvAuth;
    @BindView(RES_ID_RESET)
    TextView tvReset;
    @BindView(RES_ID_HEAD)
    TouchImageView ivHead;
    private CoachVerificationActivity $this;

    private boolean isAuth = false;
    private Bitmap bitmap;

    /**
     * TODO 界面跳转，传参需定义
     *
     * @param context
     */
    public static void startActivity(Context context) {
        Intent intent = new Intent(context, CoachVerificationActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected void init() {
        super.init();
        $this = this;
        setContentView(RES_ID_LAYOUT);

    }

    @Override
    protected void initView() {
        super.initView();
        titleUtils.setTitleText("私教核销");
        titleUtils.startMainActivity(this);
    }

    @OnClick(RES_ID_AUTH)
    public void onClickForAuth(View view) {
        if (isAuth) {
            destroyCoach(Base64Util.bitmapToBase64(bitmap));
        } else {
            boolean hasPermission = true;
            if (Build.VERSION.SDK_INT >= 23) {
                String[] permissions = {Manifest.permission.READ_EXTERNAL_STORAGE};
                //验证是否许可权限
                for (String str : permissions) {
                    if ($this.checkSelfPermission(str) != PackageManager.PERMISSION_GRANTED) {
                        //申请权限
                        $this.requestPermissions(permissions, REQUEST_CODE_CONTACT);
                        hasPermission = false;
                    }
                }
            }
            if (hasPermission) {
                takePicture();
            }
        }
    }

    @OnClick(RES_ID_RESET)
    public void onClickForReset(View view) {
        boolean hasPermission = true;
        if (Build.VERSION.SDK_INT >= 23) {
            String[] permissions = {Manifest.permission.READ_EXTERNAL_STORAGE};
            //验证是否许可权限
            for (String str : permissions) {
                if ($this.checkSelfPermission(str) != PackageManager.PERMISSION_GRANTED) {
                    //申请权限
                    $this.requestPermissions(permissions, REQUEST_CODE_CONTACT);
                    hasPermission = false;
                }
            }
        }
        if (hasPermission) {
            takePicture();
        }
    }

    private void takePicture() {
        File file = new File(SDCardUtils.getHeadPath(this));
        if (!file.exists()) {
            file.mkdirs();
        }
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (intent.resolveActivity(getPackageManager()) != null) {
            startActivityForResult(intent, PHOTO_GRAPH);
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PHOTO_GRAPH:
                    if (data != null) {
                        ivHead.resetZoom();
                        tvAuth.setText("确定核销");
                        isAuth = true;
                        tvReset.setVisibility(View.VISIBLE);
                        Bundle b = data.getExtras();
                        bitmap = (Bitmap) b.get("data");
                        bitmap = BitmapUtils.resizeBitmap(bitmap, 480);
                        ivHead.setImageBitmap(bitmap);
                    } else {
                        ToastUtil.show($this, "获取图像失败");
                    }
                    break;
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_CODE_CONTACT) {
            takePicture();
        }
    }

    private void destroyCoach(String base64) {
        final SVProgressHUD svProgressHUD = new SVProgressHUD(this);
        svProgressHUD.showWithStatus("正在上传...");
        mAppHelper.apiService().destroyCoach(base64, "jpg").enqueue(new BaseCallback<ApiResponse<Object>>() {
            @Override
            public void onSuccess(Call<ApiResponse<Object>> call, Response<ApiResponse<Object>> response) {
                ToastUtil.show($this, response.body().getMsg());
                svProgressHUD.dismiss();
            }

            @Override
            public void onError(Call<ApiResponse<Object>> call, Throwable t) {
                super.onError(call, t);
                svProgressHUD.dismiss();
            }

            @Override
            public void onFailure(Call<ApiResponse<Object>> call, Throwable t) {
                super.onFailure(call, t);
                svProgressHUD.dismiss();
            }
        });
    }

}
